package pl.edu.agh.inpema.components.receivers.textFileReceiver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import pl.edu.agh.inpema.core.components.ReceiverUtil;
import pl.edu.agh.inpema.core.model.Message;

public class SimpleTextFileReceiverRunner extends Thread {
	
	private ReceiverUtil receiverUtil;
	private boolean isRunning = false;
	private boolean error = false;
	
	private static Logger logger = Logger.getLogger(SimpleTextFileReceiverRunner.class);
	
	private File dataFile = new File("resources/receivers/textFileReceiver/data1.txt");
	private int timeout = 500;

	public SimpleTextFileReceiverRunner() {
	}
	
	public void setReceiverUtil(ReceiverUtil util) {
		this.receiverUtil = util;
	}
	

	public ReceiverUtil getReceiverUtil() {
		return this.receiverUtil;
	}
	
	public void run() {
		logger.info(this.receiverUtil.getReceiverName() + ": starting...");
		this.isRunning = true;
		
			try {
				BufferedReader reader = new BufferedReader(new FileReader(dataFile));
				DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

				while(this.isRunning) {
	
					String line = reader.readLine();
					
					if (line == null) {
						logger.info(this.receiverUtil.getReceiverName() + ": no more data");
						this.isRunning = false;
					} else {
						try {
							String[] data = line.split(";");
							String login = data[0].trim();
							String ip = data[1].trim();
							String dateString = data[2].trim();
							String messageText = data[3].trim();
							Date date = df.parse(dateString);
							
							Map<String, String> messageFields = new HashMap<String, String>();
							messageFields.put(Message.FIELD_IP, ip);
							messageFields.put(Message.FIELD_DATE, ""+date.getTime());
							messageFields.put(Message.FIELD_TEXT, messageText);
							
							this.receiverUtil.addMessage(login, messageFields);
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
					
					try {
						Thread.sleep(timeout);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			} catch (IOException e) {
				e.printStackTrace();
				error = true;
			}
		logger.info(this.receiverUtil.getReceiverName() + ": finishing...");
		//System.out.println("receiver thread stop");
	}
	
	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
	
	public boolean isRunning() {
		return this.isRunning;
	}
	
	public boolean isError() {
		return this.error;
	}
	
	public void setDataFile(String fileName) {
		this.dataFile = new File(fileName);
	}
	
	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
}
